/*
 * proxy.cpp
 *
 *  Created on: Jan 18, 2016
 *      Author: root
 */

#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<errno.h>
#include<string.h>
#include<iostream>

using namespace std;

namespace dounine_proxy{

	#define BUFLEN 600
	#define title "<title>好搜 — 用好搜，特顺手</title>"
	const char target[]="GET http://www.haosou.com/\n";

	bool check_proxy(const string& ip,const int port){
		int sockfd = -1;
		char buf[BUFLEN];
		struct timeval timeout;

		int status = -1;
		fd_set rmask, wmask;
		struct sockaddr_in address;
		address.sin_family = AF_INET;
		address.sin_addr.s_addr = inet_addr(ip.c_str());
		address.sin_port = htons(port);

		sockfd=socket(AF_INET, SOCK_STREAM, 0);

		fcntl(sockfd, F_SETFL, O_NONBLOCK);

		connect(sockfd, (struct sockaddr *)&address, sizeof(address));

		timeout.tv_sec = 3;//timeout times 1s
		timeout.tv_usec = 0;
		FD_ZERO(&wmask);
		FD_SET(sockfd, &wmask);
		status = select(sockfd+1, NULL, &wmask, NULL, &timeout);
		if(status==0){
			close(sockfd);
		}else{
			if(!FD_ISSET(sockfd, &wmask)){
				close(sockfd);
			}
		}
		status = write(sockfd, target, sizeof(target));
		timeout.tv_sec = 1;
		timeout.tv_usec = 0;
		FD_ZERO(&rmask);
		FD_SET(sockfd, &rmask);
		status = select(sockfd+1, &rmask, NULL, NULL, &timeout);
		if(status==1){
			if(FD_ISSET(sockfd, &rmask)){
				memset(&buf,0, BUFLEN);
				status = read(sockfd, buf, BUFLEN);
				close(sockfd);
				char *cc;
				if((cc = strstr(buf,title))){
					cout<<"find free proxy ip address => "<<ip<<":"<<port<<endl;
					return true;
				}else{
					cout<<cc<<endl;
				}
			}
		}
		return false;
	}
}
